// AI Assistant Service
// This service handles AI assistant functionality and API calls

import { getAIConfig, getAPIHeaders } from './aiConfigService';

/**
 * Send a message to AI assistant
 * @param {string} message - User message
 * @param {Array} context - Optional context information
 * @returns {Promise} AI response
 */
export const sendMessageToAI = async (message, context = []) => {
  try {
    const config = getAIConfig();
    
    if (!config.apiToken) {
      throw new Error('AI API token not configured');
    }
    
    // Prepare the conversation context
    const systemPrompt = '你是一个友好的AI助手，专门帮助用户使用时光相册应用。你可以回答关于照片管理、视频生成、相册创建等问题。请用简洁、友好的语气回答，如果用户询问技术问题，请提供清晰的步骤。请不要使用Markdown格式，直接返回纯文本。';
    
    const messages = [
      { role: 'system', content: systemPrompt },
      ...context.map(msg => ({ role: msg.role, content: msg.content })),
      { role: 'user', content: message }
    ];
    
    // Prepare API request based on provider
    let requestData, endpoint;
    
    if (config.provider === 'openai' || config.provider === 'openai-compatible') {
      endpoint = `${config.endpoint}/chat/completions`;
      requestData = {
        model: config.model,
        messages,
        max_tokens: config.maxTokens,
        temperature: config.temperature
      };
    } else if (config.provider === 'anthropic') {
      endpoint = `${config.endpoint}/messages`;
      requestData = {
        model: config.model,
        max_tokens: config.maxTokens,
        temperature: config.temperature,
        messages: messages.filter(msg => msg.role !== 'system')
      };
    } else {
      throw new Error('Unsupported AI provider');
    }
    
    // Make API request
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: getAPIHeaders(),
      body: JSON.stringify(requestData)
    });
    
    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }
    
    const data = await response.json();
    
    // Extract response based on provider
    let aiResponse;
    if (config.provider === 'openai' || config.provider === 'openai-compatible') {
      aiResponse = data.choices[0]?.message?.content || '抱歉，我无法回答这个问题。';
    } else if (config.provider === 'anthropic') {
      aiResponse = data.content[0]?.text || '抱歉，我无法回答这个问题。';
    }
    
    // Remove Markdown formatting from the response
    aiResponse = aiResponse.replace(/\*\*(.*?)\*\*/g, '$1'); // Remove **text**
    aiResponse = aiResponse.replace(/\*(.*?)\*/g, '$1');     // Remove *text*
    aiResponse = aiResponse.replace(/`(.*?)`/g, '$1');       // Remove `text`
    aiResponse = aiResponse.replace(/#{1,6}\s/g, '');        // Remove # headers
    aiResponse = aiResponse.replace(/\[(.*?)\]\(.*?\)/g, '$1'); // Remove [text](url)
    
    return {
      success: true,
      message: aiResponse,
      timestamp: new Date().toISOString()
    };
  } catch (error) {
    console.error('Error sending message to AI:', error);
    
    // Return a fallback response for demo purposes
    return {
      success: false,
      message: getFallbackResponse(message),
      timestamp: new Date().toISOString(),
      error: error.message
    };
  }
};

/**
 * Get fallback response for demo purposes when API is not available
 * @param {string} message - User message
 * @returns {string} Fallback response
 */
const getFallbackResponse = (message) => {
  const lowerMessage = message.toLowerCase();
  
  // Simple keyword-based responses for demo
  if (lowerMessage.includes('照片') || lowerMessage.includes('图片')) {
    return '您可以在"上传"页面添加照片，或在"时光线"和"相册"中查看已上传的照片。需要我帮您导航到这些页面吗？';
  }
  
  if (lowerMessage.includes('视频') || lowerMessage.includes('ai')) {
    return '您可以使用AI视频生成功能将照片转换为精彩视频。请前往"AI视频"页面，上传照片并选择视频风格。记得先在设置中配置AI API密钥哦！';
  }
  
  if (lowerMessage.includes('相册')) {
    return '在"相册"页面，您可以创建新相册来组织照片，也可以查看和管理现有相册。点击"创建相册"按钮开始整理您的美好回忆！';
  }
  
  if (lowerMessage.includes('帮助') || lowerMessage.includes('help')) {
    return '我是您的AI助手，可以帮助您了解时光相册的各项功能。您可以问我关于照片管理、视频生成、相册创建等问题。有什么需要帮助的吗？';
  }
  
  return '感谢您的提问！我是时光相册的AI助手，可以帮助您了解应用功能。您可以问我关于照片管理、视频生成、相册创建等问题。';
};

/**
 * Get suggested questions for the AI assistant
 * @returns {Array} Array of suggested questions
 */
export const getSuggestedQuestions = () => {
  return [
    '如何上传照片？',
    '如何创建相册？',
    '如何生成AI视频？',
    '如何分享照片？',
    '时光线是什么？',
    '如何设置个人资料？'
  ];
};

/**
 * Get conversation history from localStorage
 * @returns {Array} Conversation history
 */
export const getConversationHistory = () => {
  try {
    const history = localStorage.getItem('aiAssistantHistory');
    return history ? JSON.parse(history) : [];
  } catch (error) {
    console.error('Error getting conversation history:', error);
    return [];
  }
};

/**
 * Save conversation to localStorage
 * @param {Array} conversation - Conversation array
 * @returns {boolean} Success status
 */
export const saveConversation = (conversation) => {
  try {
    // Keep only the last 50 messages to avoid storage issues
    const trimmedConversation = conversation.slice(-50);
    localStorage.setItem('aiAssistantHistory', JSON.stringify(trimmedConversation));
    return true;
  } catch (error) {
    console.error('Error saving conversation:', error);
    return false;
  }
};

/**
 * Clear conversation history
 * @returns {boolean} Success status
 */
export const clearConversationHistory = () => {
  try {
    localStorage.removeItem('aiAssistantHistory');
    return true;
  } catch (error) {
    console.error('Error clearing conversation history:', error);
    return false;
  }
};